let url = `http://username:password@www.baidu.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument`;
//必填 protocal hostname    http://localhost
//其它的都是可有可无的
function parseUrl(url,parseQuery=false){
   //1.声明一个正则表达式
   let pattern = /^(https?):\/\/([^:]+):([^@]+)@([^:]+):(\d+)([^?]+)\?([^#]+)#(.+)/;
   //有当前的url地址和正则进行匹配
   let result = url.match(pattern);
   //因为每一个组成部分都对应一个分组，那么可以从result中取出分组的值
   const [,protocal,username,password,hostname,port,pathname,query,hash] = result;
   //创建返回值
   let parseResult=  {
    protocal,username,password,hostname,port,pathname,query,hash
   }
   //host=主机名:端口号
   parseResult.host=hostname+":"+port;
   //path=路径名?查询字符串
   parseResult.path = pathname+'?'+query;
   //如果需要把query字符串变成对象的话
   if(parseQuery){
    let queryObj = {};
    //key1=value1&key2=value2
    parseResult.query.replace(/([^=&]+)=([^=&]+)/g,function(matched,key,value){
        queryObj[key]=value;
    });
    parseResult.query =queryObj;//parseResult.key1=value1
   }
   return parseResult
}
let result = parseUrl(url,true);
console.log(result);
/**
{
    protocal:'http',
    username:'username',
    password:'password',
    hostname:'www.baidu.com',
    port:'80',
    host:'www.baidu.com:80',
    pathname:'/path/to/myfile.html',
    query:'key1=value1&key2=value2',
    query:{key1:value1,key2:value2},
    path:'/path/to/myfile.html?key1=value1&key2=value2',
    hash:'SomewhereInTheDocument'
}
 */